package com.myk.game.gobangchess.dates;

import com.myk.game.gobangchess.DataManager;
import com.myk.game.gobangchess.Room;
import com.myk.game.gobangchess.beans.ChessPlayingBean;
import com.myk.game.gobangchess.constants.AppConfig;
import com.myk.game.gobangchess.constants.PathCost;
import com.myk.game.gobangchess.constants.WinTag;
import com.myk.game.gobangchess.rooms.absrooms.AbsAiRoom;
import com.myk.game.gobangchess.utils.DateTimeUtil;
import com.myk.game.gobangchess.utils.FileUtils;
import com.myk.game.gobangchess.utils.PathUtils;

import java.io.File;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 房间相关数据处理类
 */
public class RoomData {
    /**
     * 从在线房间列表中移除一个房间
     */
    public static void removeRoom(Room room) {
        DataManager.roomList.remove(room); //从列表中移除
        DataManager.updateRoomListConfigFile(); //更新配置文件
        DataManager.noticeAllRefreshRoomList(); //通知大厅玩家刷新列表
        DataManager.printRoomList();//打印到控制台
    }

    /**
     * 根据一个已经存在的房间克隆新房间，
     * 排序在一起，各项配置相同
     */
    public static void cloneRoom(Room exitRoom, String newRoomName) throws Exception {
        Room newRoom = exitRoom.getClass().getConstructor(String.class).newInstance(newRoomName);
        newRoom.setSaveHistoryToFile(exitRoom.isSaveHistoryToFile());
        newRoom.setCurRoomMode(exitRoom.getCurMode());
        newRoom.setRoomIntroduce(exitRoom.getRoomIntroduce());
        newRoom.setSorterOrder(exitRoom.getSorterOrder());
        newRoom.onCreatePrepare();
        int index = DataManager.roomList.indexOf(exitRoom);
        DataManager.roomList.add(index, newRoom); //添加新房间到列表中
        DataManager.updateRoomListConfigFile(); //更新配置文件
        DataManager.printRoomList();//打印到控制台
    }

    /**
     * 根据元数据反射创建新房间
     */
    public static void createRoom(String className, String chessName, String roomName, boolean isSaveReport, String modeName, String introduce) throws Exception {
        Class<?> roomClass = Class.forName("com.myk.game.gobangchess.rooms" + "." + className);
        Room room = (Room) roomClass.getConstructor(String.class).newInstance(roomName);
        room.setSaveHistoryToFile(isSaveReport);
        room.setCurRoomMode(modeName);
        room.setRoomIntroduce(introduce);
        room.setSorterOrder(DataManager.roomList.get(0).getSorterOrder() - 1);
        room.onCreatePrepare();
        DataManager.roomList.add(0, room); //添加新房间到列表最上方
        DataManager.updateRoomListConfigFile(); //更新配置文件
        DataManager.printRoomList();//打印到控制台
    }

    /**
     * 获取所有可玩棋类列表，在myk.game.gobangchess.rooms下的所有Room类
     */
    public static List<Room> getChessListInfo() {
        List<Room> chessList = new ArrayList<>();
        String rootPath = PathUtils.getRootPath();
        String packageName = "com.myk.game.gobangchess.rooms";
        String packagePath = packageName.replace(".", "/");
        File roomsDir = new File(rootPath + "/" + packagePath);
        if (roomsDir.exists() && roomsDir.isDirectory()) {
            List<File> chessFileList = FileUtils.listFilesInDir(roomsDir);
            for (File file : chessFileList) {
                String chessClassName = file.getName();
                if (chessClassName.contains(".class") && !chessClassName.contains("$")) {
                    try {
                        Class<?> chessClass = Class.forName(packageName + "." + chessClassName.replace(".class", ""));
                        Room room = (Room) chessClass.getConstructor(String.class).newInstance("房间名");
                        chessList.add(room);
                    }
                    catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return chessList;
    }

    /**
     * 获取某个棋已经配置的房间的数量
     */
    public static int getChessRoomNum(String chessName) {
        int num = 0;
        for (Room room : DataManager.roomList) {
            if (room.getChessName().equals(chessName)) num++;
        }
        return num;
    }

    /**
     * 获取一个房间的详细配置信息
     */
    public static String getRoomConfigInfo(String roomName) {
        Room room = DataManager.getRoomByName(roomName);
        if (room != null) {
            return "类名：" + room.getClass().getSimpleName() + "\n" +
                    "棋名：" + room.getChessName() + "\n" +
                    "房间名：" + roomName + "\n" +
                    "准入人数：" + room.getPlayerMax() + "\n" +
                    "当前模式：" + room.getCurMode() + "\n" +
                    "是否可以单人对弈：" + room.isSupportPersonal() + "\n" +
                    "是否可以保存战报：" + room.isSaveHistoryToFile() + "\n" +
                    "房间简介：" + "\n" + room.getRoomIntroduce();
        }
        return "-1";
    }

    /**
     * 获取所有棋所有对弈情况（以rooms包内的为主去查，忽略ai房间）
     */
    public static List<ChessPlayingBean> getAllChessPlayingList() {
        List<ChessPlayingBean> chessPayingList = new ArrayList<>();
        List<Room> chessListInfo = getChessListInfo();
        for (Room room : chessListInfo) {
            if (room instanceof AbsAiRoom) continue; //忽略AI房间
            String className = room.getClass().getSimpleName();
            String chessName = room.getChessName();
            List<ChessPlayingBean.PlayingRecordBean> recordList = getRoomPlayingList(className);
            ChessPlayingBean chessPlayingBean = new ChessPlayingBean(className, chessName, recordList);
            chessPayingList.add(chessPlayingBean);
        }
        return chessPayingList;
    }

    /**
     * 获取某个棋的所有对弈情况
     */
    public static List<ChessPlayingBean.PlayingRecordBean> getRoomPlayingList(String className) {
        List<ChessPlayingBean.PlayingRecordBean> recordList = new ArrayList<>();
        String dirPath = PathCost.RECORDS_DIR + className;
        if (FileUtils.isFileExists(dirPath)) {
            List<File> fileList = FileUtils.listFilesInDir(dirPath);
            if (fileList.size() > 0) {
                for (File file : fileList) {
                    try {
                        /*文件格式形如   震棋_测试A(胜)_vs(35)_测试B(负)_20230928151246.txt   */
                        String fileName = file.getName();
                        fileName = fileName.substring(0, fileName.indexOf(".txt"));
                        String[] metaData = fileName.split("_");
                        /*统计时间*/
                        String timeStr = metaData[4];
                        /*获取对弈玩家昵称和胜负数据*/
                        String blackName = metaData[1].substring(0, metaData[1].indexOf("("));
                        String whiteName = metaData[3].substring(0, metaData[3].indexOf("("));
                        recordList.add(new ChessPlayingBean.PlayingRecordBean(blackName, whiteName, timeStr));
                    }
                    catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return recordList;
    }
}
